<?php

class MakerController extends SBaseController {

    public $layout = 'main';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * Displays a particular model.
     */
    public function actionView() {
        $this->layout = "detail";
        $this->render('view', array(
            'model' => $this->loadModel(),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Maker();
        $model->status = Lvc::STATUS_ENABLED;
        $model->sorder = Common::getNewestPosition($model);
        $this->pageTitle = Yii::t('BackEnd', 'Create') . Yii::t('BackEnd', 'maker');
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Maker'])) {
            $model->attributes = $_POST['Maker'];
            if ($model->validate()) {
                if ($model->insert()) {
                    Yii::app()->user->setFlash('message', Yii::t('Global', 'Create successfully.'));
                    $this->redirect(array('view', 'id' => $model->id));
                }
            }
        }

        $this->layout = "detail";
        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate() {
        $model = $this->loadModel();

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        $this->pageTitle = Yii::t('BackEnd', 'Create') . Yii::t('Update', 'maker');

        if (isset($_POST['Maker'])) {
            $model->attributes = $_POST['Maker'];
            if ($model->validate()) {
                if ($model->update()) {
                    Maker::model()->rebuildSOrder();
                    Yii::app()->user->setFlash('message', Yii::t('Global', 'Update successfully.'));
                    $this->redirect(array('view', 'id' => $model->id));
                }
            }
        }

        $this->layout = "detail";
        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     */
    public function actionDelete() {
        if (isset($_POST['select-row']) && is_array($_POST['select-row'])) {
            $ids = $_POST['select-row'];
            $ids = implode(',', $ids);
            Maker::model()->deleteAll("id in ($ids)");
            $this->redirect(array('admin'));
        } elseif (Yii::app()->request->isPostRequest) {
            $model = $this->loadModel();
            $model->delete();
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        if (!isset($_GET['ajax']) && isset($_POST['sorder'])) {
            $ids = $_POST['ids'];
            $sorder = $_POST['sorder'];
            for ($i = 0; $i < count($ids); $i++) {
                $model = Maker::model()->findByPk($ids[$i]);
                $model->sorder = $sorder[$i];
                $model->save();
            }
            Maker::model()->rebuildSOrder();
            Yii::app()->user->setFlash('message', Yii::t('BackEnd', 'Rebuild all sort order successfully.'));
        }

        $model = new Maker('search');
        $model->sorder = '';
        $model->status = '';
        if (isset($_GET['Maker']))
            $model->attributes = $_GET['Maker'];

        $this->layout = "list";
        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel() {
        if ($this->_model === null) {
            if (isset($_GET['id']))
                $this->_model = Maker::model()->findbyPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'maker-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionChangeStatus() {
        if ($_POST['ajax'] && $_POST['id']) {
            $model = Maker::model()->findByPk($_POST['id']);
            if ($model->status == Lvc::STATUS_ENABLED)
                $model->status = Lvc::STATUS_DISABLED;
            elseif ($model->status == Lvc::STATUS_DISABLED)
                $model->status = Lvc::STATUS_ENABLED;
            $model->save();
            Yii::app()->end();
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    public function actionCheckName() {
        if (Yii::app()->request->isPostRequest) {
            $data = Lvc::selectOne(Maker::model()->tableName(), 'id', 'maker_name="' . $_POST['name'] . '" ');
            $id = $data['id'];
            if ($id) {
                $array = array(
                    "success" => true,
                    'link' => '<a href="' . Yii::app()->createUrl('Maker/view', array('id' => $id)) . '" >' . Yii::t('BackEnd', 'Name exit.') . '</a> '
                );
                echo json_encode($array);
            }
            else
                echo '{"success":false}';
            Yii::app()->end();
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

}
